<?php

namespace App\Console\Commands;

use App\Clients\JinShouFu\LoadLineChartData;
use App\Clients\JinShouFu\StoreIncome;
use App\Clients\JinShouFu\StoreList;
use App\Clients\Keruyun\IncomeListByPage;
use App\Clients\Keruyun\StoreQueryOrgTree;
use App\Clients\Lakala\AccountAuthUserInfo;
use App\Clients\MeiTuan\AdminH5LoginConfig;
use App\Clients\YikaCar\YikaBike;
use App\Clients\Yisheng\CompanyInfo;
use App\Models\Account;
use App\Models\AccountMapping;
use App\Models\AccountSub;
use App\Models\Mall;
use App\SDK\PingAn\Service;
use App\Services\JinShouFuHelper;
use App\Utils\AesCrypto;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;

class TextCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     * @throws Exception
     * @throws GuzzleException
     */
    public function handle()
    {
        $s = 'eyJpdiI6IlFuaEZPVGFCYmRPT3JJTTNnQnZwZVE9PSIsInZhbHVlIjoiNmdRcmJvaCtwcS9oNGtMVG82MjJwZW11SHNuditHNnRiQncvM09GaFIwQT0iLCJtYWMiOiJhZTRiMTQ4OWIzY2JjZWNiOWZhYjBlZjJmZDI1NzY0YmVmZTVkOTNmMWQ2MTc5ZTVkNzA5Y2Q4ZjRmYjg2MDNmIiwidGFnIjoiIn0=';
        var_dump(Crypt::decrypt($s));
        exit();


//        $s = file_get_contents("https://www.jsfpay.com/orderflow/orderflowlistSale.do");
//        var_dump($s);
//        exit();
//        $account = Account::query()->find(4);
//        $service = new CompanyInfo($account);
//        $queryData = [];
//        $response = $service->loopExecute($queryData)->contents();
//        var_dump($response);
//        exit();

        $account = AccountSub::query()->find(6);
        $service = new YikaBike($account);
        $queryData = [

        ];
        $response = $service->loopExecute($queryData)->contents();
        var_dump($response);
        exit();

        $helper = new JinShouFuHelper;
        $key = $helper->setKey("MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANL378k3RiZHWx5AfJqdH9xRNBmD9wGD\n2iRe41HdTNF8RUhNnHit5NpMNtGL0NPTSSpPjjI1kJfVorRvaQerUgkCAwEAAQ==");
        $password = $helper->encrypt("045411",$key);
        var_dump($password);
        exit();

        $account = Account::query()->find(3);
        //$client = new StoreQueryOrgTree($account);
        $client = new IncomeListByPage($account);
        $queryData = [
            "merchantNo"=>"40282015",
            "startDate"=>intval(strtotime(date("2025-08-10")) * 1000),
            "endDate"=>intval(strtotime(date("2025-08-10 23:59:59")) * 1000),
        ];
        $client->handleQueryData($queryData);
        $response = $client->loopExecute(null)->contents();
        var_dump($response);
        exit();


        $s = '{"group":"HSF","@class":"com.alsc.saas.gw.client.HsfReq","service":"com.alsc.saas.resource.business.gw.client.hm.HmDataTransportClient","method":"queryAreaDataV3","version":"1.0.0","eagleEyeUserData":{},"argTypes":["com.alsc.saas.resource.business.gw.client.hm.req.HmAreaDataReq"],"argValues":[{"area":[{"areaId":"100410041","methodName":"indexV4","intefaceName":"com.alsc.saas.data.reportcenter.sdk.client.gw.frontend.order.external.overview.business.v3.index.IndexQueryClientV3","class":"com.alsc.saas.resource.business.gw.client.hm.req.HmAreaDataReq$HmAppDataProviderDescReq","jsonParam":"{\"permissionContext\":{\"appName\":\"HOME_PC\",\"businessScene\":\"HOME_PC\",\"serviceName\":\"HOME_PC\"},\"class\":\"com.alsc.saas.data.reportcenter.sdk.client.gw.frontend.order.external.overview.business.v3.req.index.IndexQueryReqV3\",\"currentTime\":1754986918908,\"startTime\":1754928000000,\"endTime\":1755014399999,\"previousStartTime\":1754323200000,\"previousEndTime\":1754409599999,\"currentBusiDateTime\":1754928000000,\"indexTypeList\":[\"UNFINISHED_ORDER_INCOME_AMT\",\"UNFINISHED_ORDER_CNT\",\"FINISHED_INCOME_AMT\",\"FINISHED_ORDER_CNT\",\"ESTIMATE_INCOME_AMT\",\"ESTIMATE_ORDER_CNT\",\"ESTIMATE_DINERS_CNT\",\"INCOME_AMT_PERSON_AVG\"]}","enableRevealAllTheDetail":true,"version":"1.0.0","group":"HSF"}],"saasEmployeeId":"2220337384467","reqSource":"WEB_BUSINESS_MANAGER","industryType":"DINNER","reqVersion":"","templateId":"1004","saasOrgGroupId":"40306019","saasBrandId":"40266021","saasShopId":"40282015","orgGroupId":"","brandId":"40266021","shopId":"40282015","deviceId":"","operatorUserId":"2220337384467","operatorUserName":"鑫亿捷","userType":"PC"}],"targetClusterName":"alibaba-prod","timeout":"PT30S","context":{"visitedDevice":"WEB"}}2/ESvw==';

        var_dump(md5($s));
        exit();

        $plaintext = 'jiang123';
        $key = 'kry-login-202412'; // 16字节
        $iv = 'kry-login-202412';  // 16字节
        $cipher = 'AES-128-CBC';   // 明确模式（128位CBC）

// 加密（指定PKCS7填充，输出Base64）
        $ciphertext = openssl_encrypt(
            $plaintext,
            $cipher,
            $key,
            OPENSSL_RAW_DATA, // 注意：PHP中PKCS7是默认，无需额外指定
            $iv
        );
//        var_dump();
//        exit();
        $ciphertextBase64 = base64_encode($ciphertext);
        var_dump($ciphertextBase64);
        exit();

        $datas = openssl_encrypt("jiang123","AES-256-CBC","kry-login-202412",OPENSSL_RAW_DATA,"kry-login-202412");
        var_dump($datas);
        exit();
        // 密钥和密文
        $secretKey = 'kry-login-202412';
        $encryptedStr = 'U2FsdGVkX19Dy6s/L2n2BB1DA2gKRxg4Jo/zPUpIy20=';

        // 创建实例
        $aes = new AesCrypto($secretKey);

        // 解密操作
        $decrypted = $aes->decrypt($encryptedStr);
        echo "密文: {$encryptedStr}\n";
        echo "解密结果: {$decrypted}\n";  // 应输出: jiang123

        // 加密验证（使用相同参数加密明文，验证是否匹配）
        $testEncrypt = $aes->encrypt('jiang123');
        echo "验证加密: {$testEncrypt}\n";
        echo "验证解密: {$aes->decrypt($testEncrypt)}\n";  // 应输出: jiang123
        exit();


        $account = Account::query()->find(2);
        $service = new StoreIncome($account);
        $postData = [
            "tBegin"=>"2025-07-23 00:00:00",
            "tEnd"=>"2025-07-23 23:59:59",
            "storeId"=>"1117469931022618624",
            "sf_type"=>"2,14,15",
        ];
        $response = $service->loopExecute($postData)->contents();
        var_dump($response);
        exit();

        $service = new JinShouFuHelper();
        $sre = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCHF7+YB1eP++konjd2iwrse+S8cWUinl8LZraTZMJe/Tp6g0bn3wlA62TFhLDnWlimtlLC4MBmcMgZCu/kAYbRnSaaM4yGvuYt6CfF3AqlomSewi8crCzYbOsxWPpezCWJFo0AJmTDKhHvojLFL3uYBxvDNljkvy8Cym+ovoiPIwIDAQAB";
        $sre = $service->fromKey($sre);
        $um = $service->encrypt((string)(time() * 1000),$sre);
        $um1 = $service->encrypt("jiang123",$sre);
        var_dump($um);
        var_dump($um1);
        exit();

        $service = Service::instance();
        //$result = $service->getToken();
        $data = [
            'PageNum' => '1',
            'certificateNo'=>'91330183MAE038NT4F',
            'certificateType'=>'989',
            'account'=>'15818756820039',
            'pageNo'=>'2',
            'pageSize'=>'30',
            'requestId'=>uniqid(),
        ];
        $method = 'business/accountitem/v2/accountitem001';//请求方法，对应请求地址的最后部份
        $result = $service->invoke($data, $method);
        $total = $result["body"]["Data"]["total"];
        $totalPage = ceil($total / 30);
        for($page=1;$page<=$totalPage;$page++){
            $data = [
                'certificateNo'=>'91330183MAE038NT4F',
                'certificateType'=>'989',
                'account'=>'15818756820039',
                'pageNo'=>$page,
                'pageSize'=>'30',
                'requestId'=>uniqid(),
            ];
            $method = 'business/accountitem/v2/accountitem001';//请求方法，对应请求地址的最后部份
            $result = $service->invoke($data, $method);
//            var_dump($result["body"]["Data"]["records"][0]);
//            var_dump($result["body"]["Data"]["records"][1]);
//            exit();
            foreach ($result["body"]["Data"]["records"] as $record){
                if($record["loanType"] == "1"){
                    var_dump($record);
                    exit();
                }
//                var_dump($record);
//                exit();
//                if($record["amount"] == "1972.97"){
//                    var_dump($record);
//                    exit();
//                }
//                var_dump($record["amount"]);
//                var_dump($record["receiptNo"]);
//                var_dump($record["tradeAcctDate"]);
            }
        }
        exit();

        exit();
















        $account = Account::query()->find(1);
        $client = new AdminH5LoginConfig($account);
        $queryData = [
            "pageNo"=>1,
            "pageSize"=>500,
            "yodaReady"=>"h5",
            "csecplatform"=>"4",
            "csecversion"=>"3.2.0",
        ];
        $response = $client->execute($queryData)->contents();
        $inserts = [];
        $insertMall = [];
        foreach ($response["merchants"] as $merchant){
            if($merchant["orgType"] == 5){
                $inserts[] = [
                    "account_id"=>$account->id,
                    "merchant_no"=>$merchant["merchantNo"],
                    "mall_type"=>1,
                ];
                $insertMall[] = [
                    "merchant_no"=>$merchant["merchantNo"],
                    "name"=>$merchant["orgName"],
                    "poi_id"=>$merchant["poiId"],
                ];

            }

            foreach ($merchant["pois"] as $mer){
                $inserts[] = [
                    "account_id"=>$account->id,
                    "merchant_no"=>$mer["merchantNo"],
                    "mall_type"=>1,
                ];
                $insertMall[] = [
                    "merchant_no"=>$mer["merchantNo"],
                    "name"=>$mer["orgName"],
                    "poi_id"=>$mer["poiId"],
                ];
            }
        }

        DB::beginTransaction();
        try{
            AccountMapping::query()->upsert($inserts,["merchant_no"],["account_id","mall_type"]);
            Mall::query()->upsert($insertMall,["merchant_no"],["name","poi_id"]);
            DB::commit();
        }catch (Exception $e){
            DB::rollBack();
            throw $e;
        }




        var_dump($inserts);
        exit();
    }
}
